/*
*Copyright 2021-2023 NERCIS
*
*Licensed under the Apache License, Version 2.0 (the "License");
*you may not use this file except in compliance with the License.
*You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*Unless required by applicable law or agreed to in writing, software
*distributed under the License is distributed on an "AS IS" BASIS,
*WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*See the License for the specific language governing permissions and
*limitations under the License.
*/

package cn.ac.nercis.pes.community.component.spreadsheet.knowledge;

import cn.ac.nercis.pes.community.component.spreadsheet.TableSheetView;
import cn.ac.nercis.pes.community.model.vo.knowledge.KmUnitTargetVO;
import cn.ac.nercis.pes.model.dto.common.ItemData;
import cn.ac.nercis.pes.model.dto.knowledge.KmSimpleTargetDTO;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.control.ContextMenu;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.controlsfx.control.spreadsheet.GridBase;
import org.controlsfx.control.spreadsheet.SpreadsheetCell;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * 测评指标信息（知识库）表控件
 *
 * @author limy
 * @version 1.0.0
 */
@Slf4j
public class KmTargetSheetView extends TableSheetView<KmUnitTargetVO> {
    private final static Integer EMPTY_DATA_COUNT = 3;
    private final static List<String> COLUMNS = List.of("测评单元", "分数", "测评方法");
    private final static Integer UNIT_COLUMN_INDEX = 0;
    private final static Integer METHOD_COLUMN_INDEX = 1;
    private final static Integer DESC_COLUMN_INDEX = 2;
    private final ObservableList<ItemData> unitTargetList;

    public KmTargetSheetView() {
        this.getStyleClass().add("pes-sheet-view");
        unitTargetList = FXCollections.observableArrayList();

        var grid = new GridBase(EMPTY_DATA_COUNT, COLUMNS.size());
        grid.getColumnHeaders().addAll(COLUMNS);
        setGrid(grid);
        getColumns().get(UNIT_COLUMN_INDEX).setPrefWidth(200);
        getColumns().get(METHOD_COLUMN_INDEX).setPrefWidth(130);
        getColumns().get(DESC_COLUMN_INDEX).setPrefWidth(400);
        //this.setRequiredColumns();
    }


    public void initialize(String systemId) {
        this.editModel.set(false);
    }

    public void refreshUnitTargetData(List<KmSimpleTargetDTO> locationData) {
        this.unitTargetList.clear();
        this.unitTargetList.addAll(locationData.stream().map(item -> new ItemData(item.getName(), item.getId())).toList());
    }

    @Override
    protected void clearContent() {
        int endIndex = this.getGrid().getRows().size() - 1;
        for (; endIndex >= 0; endIndex--) {
            this.getGrid().getRows().remove(endIndex);
        }
    }

    @Override
    public void loadContent(List<KmUnitTargetVO> data) {
        this.editModel.set(false);
        this.sheetData = data;
        this.clearContent();
        for (var dataIndex = 0; dataIndex < data.size(); dataIndex++) {
            this.loadContent(data.get(dataIndex), toSheetRowIndex(dataIndex));
        }
        setGrid(getGrid());
        this.editModel.set(true);
    }

    @Override
    protected void loadContent(KmUnitTargetVO info, Integer sheetRowIndex) {
        var unitName = this.unitTargetList.stream()
                .filter(ut -> StringUtils.equals(ut.getValue(), info.getUnitTargetId()))
                .map(ItemData::getName)
                .findFirst()
                .orElse(StringUtils.EMPTY);
        final ObservableList<SpreadsheetCell> data = FXCollections.observableArrayList();
        AtomicInteger columnIndex = new AtomicInteger(0);
        data.add(getTextFieldCell(sheetRowIndex, columnIndex.getAndIncrement(), unitName, false));
        data.add(getTextFieldCell(sheetRowIndex, columnIndex.getAndIncrement(), info.getScore(), true));
        data.add(getTextAreaCell(sheetRowIndex, columnIndex.getAndIncrement(), info.getContent(), false, "data-cell-left"));
        this.getGrid().getRows().add(data);
        info.resetChange();

    }

    public List<KmUnitTargetVO> getModifyData() {
        List<KmUnitTargetVO> data = new ArrayList<>();
        for (var sheetRowIndex = 0; sheetRowIndex < this.getGrid().getRows().size(); sheetRowIndex++) {
            if (this.isEmptyData(sheetRowIndex)) {
                continue;
            }
            data.add(getModifyData(sheetRowIndex));
        }
        return data.stream()
                .filter(item -> Objects.nonNull(item) && item.isChange())
                .collect(Collectors.toList());
    }

    @Override
    public ContextMenu getSpreadsheetViewContextMenu() {
        return generateContextMenu(false);
    }


    private KmUnitTargetVO getModifyData(Integer sheetRowIndex) {
        if (toDataIndex(sheetRowIndex) < 0) {
            return null;
        }
        var rowData = this.getGrid().getRows().get(sheetRowIndex);
        KmUnitTargetVO info;
        if (toDataIndex(sheetRowIndex) < this.sheetData.size()) {
            info = this.sheetData.get(toDataIndex(sheetRowIndex));
        } else {
            return null;
        }
        var unitTargetName = StringUtils.trim(rowData.get(UNIT_COLUMN_INDEX).getText());
        var unitTargetId = this.unitTargetList.stream()
                .filter(ut -> StringUtils.equals(ut.getName(), unitTargetName))
                .map(ItemData::getValue)
                .findFirst().orElse(StringUtils.EMPTY);
        info.setUnitTargetId(unitTargetId);
        info.setScore(StringUtils.trim(rowData.get(METHOD_COLUMN_INDEX).getText()));
        info.setContent(StringUtils.trim(rowData.get(DESC_COLUMN_INDEX).getText()));
        return info;
    }

    @Override
    protected boolean validate(ObservableList<SpreadsheetCell> rowData) {
        boolean validResult = true;
        if (StringUtils.isBlank(rowData.get(UNIT_COLUMN_INDEX).getText())) {
            rowData.get(UNIT_COLUMN_INDEX).getStyleClass().add(REQUIRED_CELL_STYLE);
            validResult = false;
        } else {
            rowData.get(UNIT_COLUMN_INDEX).getStyleClass().remove(REQUIRED_CELL_STYLE);
        }
        if (StringUtils.isBlank(rowData.get(METHOD_COLUMN_INDEX).getText())) {
            rowData.get(METHOD_COLUMN_INDEX).getStyleClass().add(REQUIRED_CELL_STYLE);
            validResult = false;
        } else {
            rowData.get(METHOD_COLUMN_INDEX).getStyleClass().remove(REQUIRED_CELL_STYLE);
        }
        return validResult;
    }

    @Override
    protected void clearValidate(ObservableList<SpreadsheetCell> rowData) {
        rowData.get(UNIT_COLUMN_INDEX).getStyleClass().remove(REQUIRED_CELL_STYLE);
        rowData.get(METHOD_COLUMN_INDEX).getStyleClass().remove(REQUIRED_CELL_STYLE);
    }

    @Override
    protected boolean isEmptyData(Integer sheetRowIndex) {
        if (toDataIndex(sheetRowIndex) < 0) {
            return true;
        } else if (toDataIndex(sheetRowIndex) < this.sheetData.size()) {
            return false;
        }
        var rowData = this.getGrid().getRows().get(sheetRowIndex);
        return StringUtils.isBlank(rowData.get(UNIT_COLUMN_INDEX).getText())
                && StringUtils.isBlank(rowData.get(METHOD_COLUMN_INDEX).getText())
                && StringUtils.isBlank(rowData.get(DESC_COLUMN_INDEX).getText());
    }

    @Override
    protected ObservableList<SpreadsheetCell> generateEmptyDataRow(int dataIndex) {
        final ObservableList<SpreadsheetCell> data = FXCollections.observableArrayList();
        AtomicInteger columnIndex = new AtomicInteger(0);
        data.add(getComboBoxCell(toSheetRowIndex(dataIndex), columnIndex.getAndIncrement(), unitTargetList));
        data.add(getTextAreaCell(toSheetRowIndex(dataIndex), columnIndex.getAndIncrement(), "", true));
        data.add(getTextAreaCell(toSheetRowIndex(dataIndex), columnIndex.getAndIncrement(), "", true));
        return data;
    }

    @Override
    protected void deleteData() {

    }

    @Override
    protected List<String> getDataColumns() {
        return COLUMNS;
    }

}